package com.example.ItPhotoAlbumCloud.Service.imp;

import com.example.ItPhotoAlbumCloud.Service.ItPhotoAlbumCloudUserService;
import com.example.ItPhotoAlbumCloud.converter.ItPhotoAlbumCloudUserConverter;
import com.example.ItPhotoAlbumCloud.dto.ItPhotoAlbumCloudUserDTO;
import com.example.ItPhotoAlbumCloud.entity.ItPhotoAlbumCloudUserDO;
import com.example.ItPhotoAlbumCloud.model.PaginationDO;
import com.example.ItPhotoAlbumCloud.repository.ItPhotoAlbumCloudUserDAO;
import com.example.ItPhotoAlbumCloud.utils.CommonAssert;
import com.example.ItPhotoAlbumCloud.utils.CommonResult;
import com.example.ItPhotoAlbumCloud.utils.PaginationResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.ItPhotoAlbumCloud.utils.VerificationCodeGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;

/**
 * 云相册用户业务实现
 * 小仙 创建人 2023-03-11 14:36:11
 */
@Service
public class ItPhotoAlbumCloudUserServiceImpl implements ItPhotoAlbumCloudUserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ItPhotoAlbumCloudUserServiceImpl.class);
    @Autowired
    private JavaMailSender javaMailSender;

    private final VerificationCodeGenerator verificationCodeGenerator;
    @Resource
    private ItPhotoAlbumCloudUserDAO ItPhotoAlbumCloudUserDAO;
//    @Value("${cn.com.my.test1}")
//    private String EMAIL;
    @Override
    public CommonResult create(JSONObject request) {

        // 入参转成对应类型
        CommonAssert.isNoEmptyObj(request, "请求参数不可空");
        ItPhotoAlbumCloudUserDTO dto = JSON.toJavaObject(request, ItPhotoAlbumCloudUserDTO.class);
        // 参数校验
        CommonAssert.isNoBlankStr(dto.getCloudUserName(), "相册用户名不可空");
        CommonAssert.isNoBlankStr(dto.getCloudUserPassword(), "相册用户登录密码不可空");
        CommonAssert.isNoEmptyObj(dto.getDatae(), "注册时间不可空");
        CommonAssert.isNoBlankStr(dto.getLoggedInDevice(), "登录设备不可空");
        CommonAssert.isNoBlankStr(dto.getEmail(), "邮箱不可空");

        ItPhotoAlbumCloudUserDO dbResult = ItPhotoAlbumCloudUserDAO.queryByEmail(dto.getEmail(), dto.getCloudUserPassword());

        // 转成do模型


        // 落库
        int count = 0;
        CommonResult commonResult = null;
        if (null == dbResult) {
            ItPhotoAlbumCloudUserDO dataDo = ItPhotoAlbumCloudUserConverter.toDo(dto);
            count = ItPhotoAlbumCloudUserDAO.insert(dataDo);
            commonResult = new CommonResult(dataDo.getId());
        }

        CommonAssert.isTrue(count > 0, "邮箱已被注册，注册失败");

        // 返回创建成功的ID数据
        return commonResult;
    }

    @Override
    public CommonResult modify(JSONObject request) {

        // 入参转成对应类型
        CommonAssert.isNoEmptyObj(request, "请求参数不可空");
        ItPhotoAlbumCloudUserDTO dto = JSON.toJavaObject(request, ItPhotoAlbumCloudUserDTO.class);

        // 参数校验
        CommonAssert.isNoBlankStr(dto.getCloudUserName(), "相册用户名不可空");
        CommonAssert.isNoBlankStr(dto.getCloudUserPassword(), "相册用户登录密码不可空");
        CommonAssert.isNoEmptyObj(dto.getDatae(), "注册时间不可空");
        CommonAssert.isNoBlankStr(dto.getLoggedInDevice(), "登录设备不可空");
        CommonAssert.isNoBlankStr(dto.getEmail(), "邮箱不可空");

        // 转成do模型
        ItPhotoAlbumCloudUserDO dataDo = ItPhotoAlbumCloudUserConverter.toDo(dto);

        // 落库
        int count = ItPhotoAlbumCloudUserDAO.update(dataDo);
        CommonAssert.greaterThanZero(count, "修改失败，请重试");

        // 返回修改成功的ID数据
        return new CommonResult(dataDo.getId());
    }

    @Override
    public CommonResult pageQuery(JSONObject request) {

        // 入参基本校验
        CommonAssert.isNoEmptyObj(request, "请求参数不可空");

        // 分页信息校验
        PaginationDO pagination = PaginationDO.setRequestOffsetAndRows(request);
        CommonAssert.isNoEmptyObj(pagination, "分页参数 $pageIndex、$pageSize 不可空");
        CommonAssert.isTrue(pagination.getPageSize() <= 100, "单次查询条数不可超过100条");

        // 取分页列表数据
        List<ItPhotoAlbumCloudUserDO> dbResult = ItPhotoAlbumCloudUserDAO.pageQuery(request);

        // 取count数据
        long count = ItPhotoAlbumCloudUserDAO.pageQueryCount(request);

        // 空返回
        if (CollectionUtils.isEmpty(dbResult)) {
            return new CommonResult(new PaginationResult(null, request, count));
        }

        // 模型转换
        List<ItPhotoAlbumCloudUserDTO> list = ItPhotoAlbumCloudUserConverter.toDtoList(dbResult);

        // 返回分页结果
        return new CommonResult(new PaginationResult(list, request, count));
    }

    @Override
    public CommonResult queryByEmail(JSONObject request) {

        // 取入参
        CommonAssert.isNoEmptyObj(request, "请求参数不可空");

        // 根据email获取数据
        String email = request.getString("email");
        String CloudUserPassword = request.getString("CloudUserPassword");
        System.out.println(CloudUserPassword);
        CommonAssert.isNoEmptyObj(email, "参数错误，无法执行查询");
        CommonAssert.isNoEmptyObj(CloudUserPassword, "参数错误，无法执行查询");
        ItPhotoAlbumCloudUserDO dbResult = ItPhotoAlbumCloudUserDAO.queryByEmail(email, CloudUserPassword);

        // 未查询到结果，返回
        if (null == dbResult) {
            return new CommonResult();
        }

        // 模型转换
        ItPhotoAlbumCloudUserDTO result = ItPhotoAlbumCloudUserConverter.toDto(dbResult);

        // 返回结果对象
        return new CommonResult(result);
    }

//    private final JavaMailSender javaMailSender;


    public ItPhotoAlbumCloudUserServiceImpl(JavaMailSender javaMailSender, VerificationCodeGenerator verificationCodeGenerator) {
        this.javaMailSender = javaMailSender;
        this.verificationCodeGenerator = verificationCodeGenerator;
    }
    @Override
    public CommonResult sendHtmlEmail(JSONObject request) {
        // 根据email获取数据
//        SimpleMailMessage message = new SimpleMailMessage();

        String email = request.getString("email");
        String code = verificationCodeGenerator.generateCode(email);
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        String result = "验证码发送成功";
        try {
            helper = new MimeMessageHelper(message, true, "utf-8");
            message.setFrom("3433087132@qq.com");
            helper.setSubject("回忆相册验证码");
            helper.setTo(email);
            System.out.println(email);
            helper.setText(
                    "<!DOCTYPE html><html lang=\"zh-CN\"><head><title>回忆相册</title>" +
                    "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><meta name=\"viewport\"content=\"width=device-width, initial-scale=1\">" +
                    "</head><body><div style=\"background-color: #f2f2f2; padding: 20px;\"><h2 style=\"color: #444444;" +
                    " font-size: 24px; font-weight: bold; margin: 0;\">回忆相册</h2><p style=\"color: #666666; font-size: 16px;" +
                    " margin-top: 10px;\">请使用以下验证码进行验证:</p><div style=\"background-color: #ffffff; border: 1px solid #dddddd;" +
                    " padding: 10px; margin-top: 10px;\"><p style=\"color: #444444; font-size: 18px; font-weight: bold; margin: 0;\">"+code+"</p></div>" +
                    "<p style=\"color: #666666; font-size: 16px; margin-top: 10px;\">此验证码将在60秒后失效，请尽快使用。</p></div></body></html>",
                    true);
            javaMailSender.send(message);

        } catch (MessagingException e) {
            result = "验证码发送失败";
            throw new RuntimeException(e);
        }


        return new CommonResult(result);
    }
}

